<?php

namespace App\Console\Commands\Tasks;

use App\Models\ActivityDB\Love5202022GiftRank;
use App\Models\ActivityDB\Love5202022Setting;
use Carbon\Carbon;
use Illuminate\Console\Command;

class ScriptFix520GiveGiftCommand extends Command
{
    //命令名
    protected $signature = 'task:fix_gift {ids?}';

    //命令描述:修复520礼物记录
    protected $description = 'fix gift for 520 activity';

    public function __construct()
    {
        parent::__construct();
    }

    //业务处理
    public function handle()
    {
        $ids = $this->argument("ids");
        $setting = (new Love5202022Setting())->newQuery()->find(1);
        $giftIds = explode(',',$setting->gift_ids);
        if ($ids) {
            $idsArr = explode(',', $ids);
            //修复指定的id记录
            $items = app('model_give_gift')->newQuery()->whereIn('id', $idsArr)
                ->whereIn('gift_id', $giftIds)->get();
        } else {
            $start_at = Carbon::parse('2022-5-20 00:00:00')->timestamp;
            $end_at = Carbon::parse('2022-5-20 00:47:00')->timestamp;
            $items = app('model_give_gift')->newQuery()->whereIn('gift_id', $giftIds)
                ->whereBetween('add_time', [$start_at, $end_at])->get();
        }

        $success = $fail = [];
        $model = new Love5202022GiftRank();
        foreach ($items->toArray() as $item) {
            try {
                $model->add($item);
                $success[] = $item['id'];
            } catch (\Exception $exception) {
                $fail[] = $item['id'];
            }
        }
        echo json_encode(['success' => $success, 'fail' => $fail]) . PHP_EOL;
    }

}
